package jjn.carl.binary_tree;

import commons.BinaryTreeHelper;
import commons.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-07-15 23:59
 */
public class LeetCode404 {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return dfs(root);
    }
    
    private int dfs(TreeNode node) {
        int ans = 0;
        if (node.left != null) {
            ans += isLeafNode(node.left) ? node.left.val : dfs(node.left);
        }
        if (node.right != null && !isLeafNode(node.right)) {
            ans += dfs(node.right);
        }
        return ans;
    }
    
    private boolean isLeafNode(TreeNode node) {
        return node != null && node.left == null && node.right == null;
    }
    
    public static void main(String[] args) {
        // [3,9,20,null,null,15,7]
        List<Integer> input = new ArrayList<>();
        input.addAll(List.of(3, 9, 20));
        input.add(null);
        input.add(null);
        input.addAll(List.of(15, 7));
        TreeNode root = BinaryTreeHelper.buildTree(input);
        int sumOfLeftLeaves = new LeetCode404().sumOfLeftLeaves(root);
        System.out.println("sumOfLeftLeaves = " + sumOfLeftLeaves);
    }
}
